<?php defined("MAIN_DIR") or die("No direct access");

$error = array();
if (isset($_POST['action']) && $_POST['action'] == "add")
{
	$captions = array();
	$text = filter_var($_POST['text'],FILTER_SANITIZE_MAGIC_QUOTES);
	$answers_count = filter_var($_POST['answers_count'],FILTER_SANITIZE_MAGIC_QUOTES);
	for ($i = 0; $i < $answers_count; $i++)
		$captions[] = filter_var($_POST['caption_'.($i+1)],FILTER_SANITIZE_MAGIC_QUOTES);
	
	if (count($error) == 0)
	{
		$add_query = "insert into `poll` (`text`) values ('$text')";
		if (mysql_query($add_query))
		{
			$poll_id = mysql_getcell("select `poll_id` from `poll` order by `poll_id` desc limit 1");
			$answers_add_query = "insert into answers (`poll_id`,`caption`) values ";
			for ($i = 0; $i < $answers_count; $i++)
			{
				$answers_add_query .= "('$poll_id','".$captions[$i]."')";
				if ($i < $answers_count - 1)
					$answers_add_query .= ", ";
			}
			
			if (mysql_query($answers_add_query)) {
				to("/admin/site/polls/");
			} else {
				$error['query'] = "Не удалось добавить";
			}
		} else {
			$error['query'] = "Не удалось добавить";
		}
	}
}

require_once ADMIN.HEADFILE;
?>
<script type='text/javascript' src='/files/js/admin/polls.js'></script>
<div align="left">
<h1>Добавление опроса</h1>
<hr /><?php
if (count($error) > 0)
	echo "<p style='color:red'>".implode("<br />",$error)."</p>";
?><form method='POST'>
<input type='hidden' name='action' id="action" value='add' />
<input type='hidden' name='answers_count' id='count' value='2' />
<table cellpadding='5' cellspacing='0'>
	<tr>
		<td width="150px">Текст вопроса</td>
		<td width="500px">
			<input style='width:100%' type='text' name='text' value='<?php if (isset($_POST['text'])) echo $_POST['text'];?>' />
		</td>
	</tr>
	<tr class='answers'>
		<td>Ответ 1</td>
		<td><input style='width:100%' type='text' name='caption_1' /></td>
	</tr>
	<tr class='answers'>
		<td>Ответ 2</td>
		<td><input style='width:100%' type='text' name='caption_2' /></td>
	</tr>
	<tr id='buttons'>
		<td colspan='2'>
			<input type='button' id='add_answer' style="width:140px;height:30px" value="Добавить ответ" />
			<input type='button' id='del_answer' style="width:140px;height:30px" value="Удалить ответ" />
		</td>
	</tr>
	<tr valign='top'>
		<td colspan='2' align="right"><button style="width:100px;height:30px" type="submit">Добавить</button></td>
	</tr>
</table>
</form>
<br /><hr /><br />
</div>

<?php require_once ADMIN.FOOTERFILE; ?>